Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:

Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:

Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode reverseBetween(ListNode head, int m, int n) {
  11. if (head == null || head.next == null) {
  12. return head;
  13. }
  14. int k = n - m + 1;
  15. ListNode f = new ListNode(0);
  16. f.next = head;
  17. ListNode p = f;
  18. ListNode c = head;
  19. // locate the m-th node
  20. while (m > 1) {
  21. p = c;
  22. c = c.next;
  23. m--;
  24. }
  25. // reverse till n-th node
  26. ListNode prev = null;
  27. ListNode curr = c;
  28. ListNode next = null;
  29. while (k > 0) {
  30. next = curr.next;
  31. curr.next = prev;
  32. prev = curr;
  33. curr = next;
  34. k--;
  35. }
  36. // re-link
  37. p.next = prev;
  38. c.next = curr;
  39. return f.next;
  40. }
  41. }